﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SelfMadeMillionaire.Core.Repositories;
using SelfMadeMillionaire.Core.Services;

namespace SelfMadeMillionaire.BLL.Services
{
    public class LogService : ILogService
    {
         private readonly ILogRepository _logRepository;
        
        public LogService(ILogRepository logRepository)
        {
            _logRepository = logRepository;
        }
        public Core.Entities.Log Add(Core.Entities.Log log)
        {
           return  _logRepository.Add(log);
            
        }

        public Core.Entities.Log Add(Exception ex)
        {
            HttpContext context = HttpContext.Current;
            string currentUser = "";
            string path = "";
            string queryString = "";
            string browser = "";
            string userHostAddress = "";
            string urlReferrer = "";

            if (context != null)
            {
                if (context.User != null)
                    currentUser = context.User.Identity.Name;
                if (context.Request != null)
                {
                    path = context.Request.Path.Replace("'", "''");
                    queryString = context.Request.QueryString.ToString();
                    browser = context.Request.Browser.Browser;
                    userHostAddress = context.Request.UserHostAddress;
                    urlReferrer = (context.Request.UrlReferrer != null ? context.Request.UrlReferrer.ToString() : "");
                }
            }

            var log = new Core.Entities.Log()
            {
                DateAdded = DateTime.Now,
                EventType = "Err",
                EventMessage =
                    (ex.InnerException != null ? ex.InnerException.Message : ex.Message).Replace("'", "''"),
                StackTrace =
                    (ex.InnerException != null ? ex.InnerException.StackTrace : ex.StackTrace).Replace("'", "''"),
                CurrentUser = currentUser,
                Path = path,
                QueryString = queryString,
                Browser = browser,
                UserHostAddress = userHostAddress,
                UrlReferrer = urlReferrer
            };

            try
            {
                return Add(log);
            }
            catch
            {
                throw ex;
            }
        }
        
    }
}
